package com.etoak.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.etoak.commons.util.ValidatorUtil;
import com.etoak.entity.Car;
import com.etoak.mapper.AreaMapper;
import com.etoak.mapper.CarMapper;
import com.etoak.service.CarService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.Data;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author et2108
 * @since 2021-12-13
 */
@Service
@Transactional(propagation = Propagation.REQUIRED,
isolation = Isolation.DEFAULT,
rollbackFor =  Throwable.class)
public class CarServiceImpl extends ServiceImpl<CarMapper, Car> implements CarService {

    @Autowired
    CarMapper carMapper;
    @Autowired
    AreaMapper areaMapper;

    @Override
    public int addCar(Car car) {
        //校验
        ValidatorUtil.validate(car);

        //设置location
       List<Integer>   idList =  Arrays.asList(car.getCity(),car.getArea());
        List<String> nameList = areaMapper.getNameList(idList);

        if (CollectionUtils.isEmpty(nameList)||nameList.size()!=2){
            throw  new  RuntimeException("city/area字段错误");
        }
        String location = StringUtils.join(nameList, "-");
        car.setLocation(location);


        // 创建时间
        String createTime = LocalDateTime.now()
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd  HH:mm:ss"));
        car.setCreateTime(createTime);
        return carMapper.insert(car);


    }
}
